<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
        <!-- 按钮区 -->
      <el-row>
          <el-col>
              <el-button type="primary" @click="showAddDialogVisible">添加分类</el-button>
          </el-col>
      </el-row>
          <!-- 表格区 -->
          <tree-table
          class="treeTable"
          :data="catelist"
          :columns="columns"
          show-index
          index-text='#'
          border
          :show-row-hover="false"
          :expand-type="false"
          :selection-type="false">
              <template slot="isok" slot-scope="scope">
                  <i class="el-icon-success" v-if="scope.row.cat_deleted === false"
                    style="color:lightgreen"></i>
                  <i class="el-icon-error" v-else style="color:red"></i>
              </template>
            <!-- level -->
            <template slot="level" slot-scope="scope">
                  <el-tag size="mini" v-if="scope.row.cat_level === 0">等级一</el-tag>
                  <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">等级二</el-tag>
                  <el-tag size="mini" type="warning" v-if="scope.row.cat_level === 2">等级三</el-tag>
            </template>
            <!-- 操作 -->
            <template slot="opt" slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)" >编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeCate(scope.row.cat_id)" >删除</el-button>
            </template>
          </tree-table>
      <!-- 分页区 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加商品分类的对话框 -->
    <el-dialog
          title="添加商品分类"
          :visible.sync="addDialogVisible"
          width="50%" @close='addDialogClose'>
          <!-- 内容区 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
            <el-form-item label="分类名称" prop="cat_name">
              <el-input v-model="addForm.cat_name"></el-input>
            </el-form-item>
            <el-form-item label="父级分类">
                <!-- optiops 用来指定数据源 -->
                <el-cascader
                  clearable
                  v-model="selectKeys"
                  :options="parentCateList"
                  :props="cascaderProps"
                  @change="parentCateChange">
                </el-cascader>
            </el-form-item>
          </el-form>
          <!-- 底部区 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCate" >确 定</el-button>
          </span>
    </el-dialog>

    <!-- 编辑商品分类的对话框 -->
        <el-dialog
          title="编辑商品分类"
          :visible.sync="editDialogVisible"
          width="50%" @close='editDialogClose'>
          <!-- 内容区 -->
          <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="80px">
            <el-form-item label="分类名称" prop="cat_name">
              <el-input v-model="editForm.cat_name"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部区 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editCate" >确 定</el-button>
          </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'categories',
  data () {
    return {
      // 分类列表
      catelist: [],
      total: 0,
      // 查询条件
      queryInfo: {
        pagenum: 1,
        pagesize: 10,
        type: 3
      },
      // table数据列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前列模板名称
          template: 'isok'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      // 控制添加商品分类对话框的显示与隐藏
      addDialogVisible: false,
      // 添加商品分类数据
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 10, message: '分类名称长度在2-10个字符之间', trigger: 'blur' }
        ]
      },
      // 选中的父级分类id
      selectKeys: [],
      // 父级分类列表
      parentCateList: [],
      // 指定级联选择器配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 编辑 分类 数据
      editForm: {},
      // 控制 编辑 商品分类 对话框的显示与隐藏
      editDialogVisible: false
    }
  },
  created () {
    // 获取商品分类数据
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.catelist = res.data.result
      this.total = res.data.total
      this.$message.success('获取商品分类列表成功')
      // console.log(res)
    },
    // 监听页码发生的变化
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 获取父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类列表失败')
      // this.$message.success('获取父级分类列表成功')
      this.parentCateList = res.data
    },
    // 展示添加分类对话框
    showAddDialogVisible () {
      this.getParentCateList()
      // 展示对话框
      this.addDialogVisible = true
      // console.log(this.parentCateList)
    },
    // 监听级联选择器的变化
    parentCateChange () {
      // console.log(this.selectKeys)
      // 若数组大于0 则说明选中父级分类
      if (this.selectKeys.length > 0) {
        // 父级分类的id
        this.addForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        // 当前分类的等级
        this.addForm.cat_level = this.selectKeys.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    // 监听添加商品分类对话框关闭事件
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
      this.addForm.cat_level = 0
      this.addForm.cat_pid = 0
      this.selectKeys = []
    },
    // 添加商品分类
    addCate () {
      // console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品分类失败')
        }
        this.$message.success('添加商品分类成功')
        this.addDialogVisible = false
        this.getCateList()
      })
    },
    // 展示编辑分类 获取一个商品分类信息 todo
    async showEditDialog (cateInfo) {
      const { data: res } = await this.$http.get(`categories/${cateInfo.cat_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑对话框关闭
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交编辑
    editCate () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}`, {
          cat_name: this.editForm.cat_name
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改商品分类失败')
        }
        this.$message.success('修改商品分类成功')
        this.editDialogVisible = false
        this.getCateList()
      })
    },
    // 删除分类
    async removeCate (catId) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${catId}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getCateList()
      this.$message.success('删除分类成功')
    }
  }

}
</script>

<style lang="less" scoped>
  .treeTable{
    margin-top: 15px;
  }
  .el-cascader{
    width: 100%;
  }

</style>
